#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<pthread.h>
#include<fcntl.h>
#include <ctype.h>
#include<termios.h>

#include"tcp.h"
#include"jpg.h"
#include"adc.h"
#include"datebase.h"
#include "sqliteinterface.h"

#define CAMERA_DEV_PATH	"/dev/video0"
#define ADC_DEV_PATH	"/dev/adc"
#define FILEPATH_MAX (80)


pthread_t zigbee_thread,tcp_server_thread,camera_thread,tcp_com_server_thread,screenshot_thread;
pthread_mutex_t zigbee_mutex;
pthread_mutex_t tcpServer_mutex;
pthread_mutex_t jpg_mutex;
int zigbeeFd,tcpServerFd;
struct jpg_buf_t  *jpg;
int connfd,comfd,picconfd;
int picture_num = 0;
int listenfd;

void *thread_zigbee(void *arg);
void *thread_tcpServer(void *arg);
void *thread_tcpComServer(void *arg);
void *thread_cam(void *arg);
void *thread_screen(void *arg);

int send_screenshop(int i);

int main(int argc,char *argv[])
{
	int ret,flag;
	pthread_mutex_init(&zigbee_mutex,NULL);
	pthread_mutex_init(&tcpServer_mutex,NULL);
	pthread_mutex_init(&jpg_mutex,NULL);
	
	jpg = malloc(sizeof(struct jpg_buf_t));
	printf("jpeg malloc ok \r\n");
	
	if(DB_OK != (ret = openDatabase("/mysqlite")))
	{
		printf("sqlite3_open err\r\n");
		return -1;		
	}
	printf("smart_home open ok\r\n");
	
	listenfd = tcp_server_init(NULL, "8888");
	if (listenfd == -1)
	{
		exit(EXIT_FAILURE);
	}
	else
	{
		fprintf(stdout, "init server success\n");
	}
	comfd = tcp_server_wait_connect(listenfd);
	printf("comfd socket connect\r\n");
	
	if(!(ret =  pthread_create(&tcp_com_server_thread,NULL,thread_tcpComServer,NULL)) )
	{
		printf("creat tcp_comserver thread success\r\n");
	}
	else
	{
		perror("create tcp_comserver_thread err");
		exit(EXIT_FAILURE);
	}
	if( !(ret = pthread_detach(tcp_com_server_thread)))
	{
		printf("detach tcp_com_server_thread success\r\n");
	}
	else
	{
		perror("detach tcp_com_server_thread err");
		exit(EXIT_FAILURE);
	}


	if(!(ret =  pthread_create(&zigbee_thread,NULL,thread_zigbee,(void*)&connfd)) )
	{
		printf("creat zigbee thread success\r\n");
	}
	else
	{
		perror("create zigbee thread err");
		exit(EXIT_FAILURE);
	}

	if( !(ret = pthread_detach(zigbee_thread)))
	{
		printf("detach zigbee thread success\r\n");
	}
	else
	{
		perror("detach zigbee thread err");
		exit(EXIT_FAILURE);
	}


	ret = pthread_create(&camera_thread, NULL, thread_cam, NULL);
	if (ret) {
		errno = ret;
		perror("create camera thread");
		exit(EXIT_FAILURE);
	} else
		printf("create camera thread success\n");

	ret = pthread_detach(camera_thread);
	if (ret) {
		errno = ret;
		perror("detach camera thread");
		exit(EXIT_FAILURE);
	} else
		printf("detach camera thread success\n");

    connfd = 0;
	connfd = tcp_server_wait_connect(listenfd);
	if(connfd > 0)
	{
		printf("connfd socket connect:%d\r\n",connfd);
	}
	if(!(ret =  pthread_create(&tcp_server_thread,NULL,thread_tcpServer,NULL)) )
	{
		printf("creat tcp_server thread success\r\n");
	}
	else
	{
		perror("create tcp_server_thread err");
		exit(EXIT_FAILURE);
	}
	if( !(ret = pthread_detach(tcp_server_thread)))
	{
		printf("detach tcp_server_thread success\r\n");
	}
	else
	{
		perror("detach tcp_server_thread err");
		exit(EXIT_FAILURE);
	}
	
	
	
	
	if(!(ret =  pthread_create(&screenshot_thread,NULL,thread_screen,NULL)) )
	{
		printf("creat screen thread success\r\n");
	}
	else
	{
		perror("create screen_thread err");
		exit(EXIT_FAILURE);
	}
	if( !(ret = pthread_detach(screenshot_thread)))
	{
		printf("detach screenshot success\r\n");
	}
	
	
	while(1){
	}
	
	exit(EXIT_SUCCESS);
}
	
void *thread_tcpServer(void *arg)
{

	while (1) 
	{
		if (client_process(connfd, jpg) == -1) 
		{
			tcp_server_disconnect(connfd);
			break;
		}
	}
}

void *thread_tcpComServer(void *arg)
{
	char buf[50] = {0};
	while (1) 
	{
		memset(buf,0,50);
		read(comfd,buf,20);
	 	//printf("comfd rcv:%s!\r\n",buf);
		if (strstr(buf, "DOOR_ON") != NULL)
		{
			printf("join in DOOR_ON\r\n");
			doorbell(1);
			zigbee_put_cmd(zigbeeFd,  "DOOR_ON");
		} 
		else if (strstr(buf, "OPEN_WARNING") != NULL)
		{
			printf("join in OPEN_WARNING\r\n");
			warning(1);		
		} 
		else if (strstr(buf, "CLOSE_WARNING") != NULL)
		{
			printf("join in CLOSE_WARNING\r\n");
			warning(1);	
		} 
		else if (strstr(buf, "OPEN_FAN") != NULL)
		{
	 		printf("join in OPEN_FAN\r\n");
			zigbee_put_cmd(zigbeeFd,  "OPEN_FAN");
		} 
		else if (strstr(buf, "CLOSE_FAN") != NULL)
		{
			printf("join in CLOSE_FAN\r\n");
			zigbee_put_cmd(zigbeeFd,  "CLOSE_FAN");
		}
		else if (strstr(buf, "SX") != NULL)//刷新卡号
		{
			printf("join in SX\r\n");
	
		
			char com[10] = {0};
			char Name[20] = {0};
			char Data[20] = {0};
			int data,adcFd;
			char sz[5] = {0};
			char buff[12]={0};
			sscanf(buf, "%[^-]-%[^-]-%s", com,Name,Data);//搬运工
			insertTable("RFID", Name,Data);//
			sprintf(buff,"%s%s","XG",Data);
			zigbee_put_cmd(zigbeeFd, buff);
			//zigbee发送（XG卡号）
		}
		else if (strstr(buf, "XG") != NULL)//修改密码
		{
			printf("join in XG\r\n");
	
		
			char com[10] = {0};
			char Oldpwd[20] = {0};
			char Newpwd[20] = {0};
			int data,adcFd;
			char sz[5] = {0};
			char buff[20]={0};
			sscanf(buf, "%[^-]-%[^-]-%s", com,Oldpwd,Newpwd);
			data=selectRFIDTablePwd(Oldpwd);
			printf("%d\r\n",data);
			if(data<0)
			{
				strcpy(buff,"XG-ER");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
			data = RFIDUpdataTable(Oldpwd,Newpwd);
			if(data <0)
			{
			
				strcpy(buff,"XG-ER");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
			else
			{
			
				strcpy(buff,"XG-OK");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
		}
		else if (strstr(buf, "TJ") != NULL)
		{
			char com[3] = {0};
			char Name[20] = {0};
			char Data[5] = {0};
			int data,adcFd;
			char sz[5] = {0};
			printf("join in TJ\r\n");
			printf("buf :%s\r\n",buf);		
			
			sscanf(buf, "%[^-]-%[^-]-%s", com,Name, Data);
			printf("name:%s  data:%s\r\n",Name,Data);
			data = selectWeightTable(Name);  //judge
			if(-1 == data)
			{
				insertTable("weight", Name,Data);
				sprintf(buf,"TJ-%s-%d",Name,data);
				printf("return :%s\r\n",buf);
				write(comfd,buf,20);
				continue;
			}
			/*
			sprintf(sz, "%d", data);
			printf("data:%s\r\n",sz);
			updateTable("weight", Name,Data);
			sprintf(buf,"UD-%s-%d",Name,data);
			printf("return :%s\r\n",buf);
			write(comfd,buf,20);
			*/
		}
		else if (strstr(buf, "CX") != NULL)
		{
			char Name[20] = {0};
			int data;
			int i = 0;
			printf("join in CX\r\n");
			sscanf(buf, "%*[^-]-%[^-]-%*s", Name);
			data = selectWeightTable(Name);
			if(-1 == data)
			{
				sprintf(buf,"CX-%s-%d",Name,0);
				printf("return:%d\r\n",buf);
				write(comfd,buf,20);
				continue;
			}
			printf("data:%d\r\n",data);
			sprintf(buf,"CX-%s-%d",Name,data);
			printf("return :%s\r\n",buf);
			write(comfd,buf,20);
		} 
        else if (strstr(buf, "ZC") != NULL)//注册
		{
			char com[10] = {0};
			char Name[20] = {0};
			char pwd[20] = {0};
			int data,adcFd;
			char sz[5] = {0};
			printf("join in ZC\r\n");
			//printf("buf :%s\r\n",buf);		
			char buff[20]={0};
			/*strcpy(buff,"ZC-OK");
			printf("%s\r\n",buf);
			write(comfd,buff,20);
			continue;*/
			
			sscanf(buf, "%[^-]-%[^-]-%s", com,Name, pwd);
			data = selectLogonTable(Name);///////
			if(data < 0)
			{
				
				insertTable("logon", Name,pwd);
				strcpy(buff,"ZC-OK");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
				
			}
			else
			{
				
				strcpy(buff,"ZC-ER");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
		}
		else if (strstr(buf, "DL") != NULL)//登录 
		{
			printf("join in DL\r\n");
			char buff[20]={0};
			/*strcpy(buff,"DL-OK");
			write(comfd,buff,20);
			continue;*/
			
			char com[10] = {0};
			char Name[20] = {0};
			char pwd[20] = {0};
			int data,adcFd;
			char sz[5] = {0};
			//char buff[20]={0};
			printf("join in DL\r\n");
			//printf("buf :%s\r\n",buf);		
			
			sscanf(buf, "%[^-]-%[^-]-%s", com,Name, pwd);
			data=LogonTable(Name,pwd);
			if(data>0)
			{
				
				strcpy(buff,"DL-OK");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
				
			}
			strcpy(buff,"DL-ER");
			printf("%s\r\n",buff);
			write(comfd,buff,20);
			continue;
			
		}
		else if (strstr(buf, "XG") != NULL)//修改密码
		{
			printf("join in XG\r\n");
	
		
			char com[10] = {0};
			char Oldpwd[20] = {0};
			char Newpwd[20] = {0};
			int data,adcFd;
			char sz[5] = {0};
			char buff[20]={0};
			sscanf(buf, "%[^-]-%[^-]-%s", com,Oldpwd,Newpwd);
			data=selectRFIDTablePwd(Oldpwd);
			if(data<0)
			{
				strcpy(buff,"XG-ER");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
			data=RFIDUpdataTable(Oldpwd,Newpwd);
			if(data <0)
			{
			
				strcpy(buff,"XG-ER");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;
			}
			
				strcpy(buff,"XG-OK");
				printf("%s\r\n",buff);
				write(comfd,buff,20);
				continue;

		}
		else if (strstr(buf, "ZJ") != NULL)//增加卡号//先判断卡号是否已经存在、所存在ZJ_ER，
		{									//不存在则插入发送ZJ_OK
			char com[3] = {0};
			char Name[20] = {0};
			char Data[5] = {0};
			char buff[20]={0};
			int data,adcFd;
			char sz[5] = {0};
			printf("join in ZJ\r\n");
			//printf("buf :%s\r\n",buf);		
			
			sscanf(buf, "%[^-]-%[^-]-%s", com,Name,Data);
			printf("Name:%s data:%s\r\n",Name,Data);
			//
			data = selectRFIDTable(Data);  //
			printf("%d\r\n",data);
			if(-1 == data)
			{
				data=insertTable("RFID",Name,Data);
				
				if(data>0)
				{
					strcpy(buff,"ZJ_OK");
					printf("return :%s\r\n",buff);
					write(comfd,buff,20);
					continue;
				}
			
			}
			strcpy(buff,"ZJ_ER");
			printf("return :%s\r\n",buff);
			write(comfd,buf,20);
			continue;
		}
		else if (strstr(buf, "XS") != NULL)
		{
			char Name[20] = {0};
			int data;
			int weightData[10] = {0};
			int i = 0;
			printf("join in XS\r\n");
			sscanf(buf, "%*[^-]-%[^-]-%*s", Name);
			data = showWeightTable(Name,weightData);
			if(-1 == data)
			{
				sprintf(buf,"XS-%s-%d",Name,0);
				printf("return:%d\r\n",buf);
				write(comfd,buf,20);
				continue;
			}
			printf("data:%d\r\n",data);
			sprintf(buf,"XS-%d-%d-%d-%d-%d-%d-%d-%d-%d-%d"
			,weightData[0],weightData[1],weightData[2],weightData[3]
			,weightData[4],weightData[5],weightData[6],weightData[7]
			,weightData[8],weightData[9]);
			printf("return :%s\r\n",buf);
			write(comfd,buf,50);
		}  
	}
}

	
void *thread_cam(void *arg)
{
	int i;
	int fd;
	int ret;
	unsigned int width;
	unsigned int height;
	unsigned int size;
	unsigned int index;
	unsigned int ismjpeg;
	char *yuv;
	char *rgb;

	/* A8的屏幕比较小，所以设了较低的像素 */
	width = 1024;
	height = 1024;
	fd = camera_init(CAMERA_DEV_PATH, &width, &height, &size, &ismjpeg);
	if (fd == -1)
		exit(EXIT_FAILURE);
	printf("width: %d\n", width);
	printf("height: %d\n", height);

	ret = camera_start(fd);
	if (ret == -1)
		exit(EXIT_FAILURE);

	if (!jpg) {
		perror("malloc");
		exit(EXIT_FAILURE);
	}

	if (!ismjpeg) {
		rgb = malloc(width * height * 3);
		convert_rgb_to_jpg_init();
	}

	/* 采集几张图片丢弃 */
	for (i = 0; i < 8; i++) {
		ret = camera_dqbuf(fd, (void **)&yuv, &size, &index);
		if (ret == -1)
			exit(EXIT_FAILURE);

		ret = camera_eqbuf(fd, index);
		if (ret == -1)
			exit(EXIT_FAILURE);
	}

	fprintf(stdout, "init camera success\n");


	/* 循环采集图片 */
	while (1) {
		ret = camera_dqbuf(fd, (void **)&yuv, &size, &index);
		if (ret == -1)
			exit(EXIT_FAILURE);

		/*if (ismjpeg) {
			pthread_mutex_lock(&jpg_mutex);
			memcpy(jpg->buf, yuv, size);
			jpg->len = size;
			pthread_mutex_unlock(&jpg_mutex);
		} else {
			convert_yuv_to_rgb(yuv, rgb, width, height, 24);
			pthread_mutex_lock(&jpg_mutex);
			jpg->len = convert_rgb_to_jpg_work(rgb, jpg->buf, width, height, 24, 80);
			pthread_mutex_unlock(&jpg_mutex);
		}*/
		
        convert_yuv_to_rgb(yuv, rgb, width, height, 24);
		pthread_mutex_lock(&jpg_mutex);
		jpg->len = convert_rgb_to_jpg_work(rgb, jpg->buf, width, height, 24, 80);
		pthread_mutex_unlock(&jpg_mutex);
			
		ret = camera_eqbuf(fd, index);
		if (ret == -1)
			exit(EXIT_FAILURE);
	}

	/* 代码不应该运行到这里 */
	if (!ismjpeg) {
		convert_rgb_to_jpg_exit();
		free(rgb);
	}
	free(jpg);

	ret = camera_stop(fd);
	if (ret == -1)
		exit(EXIT_FAILURE);

	ret = camera_exit(fd);
	if (ret == -1)
		exit(EXIT_FAILURE);
}
	
	
void *thread_screen(void *arg)
{
	picconfd = 0;
	int i = 0;
	picconfd = tcp_server_wait_connect(listenfd);
	if(picconfd > 0)
	{
		printf("QT had connected\n");
	}
	char commond[50] = {0};
	int ret = 0;
	while(1)
	{
		memset(commond ,0,50);
	    ret = read(picconfd,commond,50);
		printf("%s\n",commond);
	    if(strcmp(commond,"screen of picture") == 0)
	    {
			i = 0;
			printf("compare success\n");
		    send_screenshop(i);
	    }
		if(strcmp(commond,"previou picture") == 0)
		{
            printf("previou picture\n");
			i--;
			if(i < 0)
			    i = 5;
			send_screenshop(i);
		}
		if(strcmp(commond,"next picture")==0)
		{
			printf("next picture\n");
			i++;
			if(i > 5)
                i = 0;
			send_screenshop(i);
		}
	}
}
	
	
	
	
